import React, { useEffect, useMemo, useState } from "react";

import store from "../store";

const statusButtons = ["All", "UnDone", "Done"];

const colors = [
  { id: 1, name: "Red", value: "red" },
  { id: 2, name: "Blue", value: "blue" },
];

export default function TodoFooter() {
  const [state, setState] = useState(store.getState());

  const activeLength = useMemo(() => {
    return state.todos.filter((item) => !item.done).length;
  }, [state]);

  const deActiveLength = useMemo(() => {
    return state.todos.filter((item) => item.done).length;
  }, [state]);

  function fn1(status) {
    return () => {
      store.dispatch({ type: "STATUS_CHANGE", status });
    };
  }

  function fn2(value) {
    return () => {
      store.dispatch({ type: "COLORS_CHANGE", color: value });
    };
  }

  useEffect(() => {
    const unsubscribe = store.subscribe(() => {
      console.log("TodoFooter subscribe");
      setState(store.getState());
    });

    return () => {
      // 取消订阅
      unsubscribe();
    };
  }, []);

  return (
    <div className="todo-footer">
      <div className="todo-statistics">
        {/* <div>
          进行中 - <span>{activeLength}</span>个
        </div>
        <div>
          已完成 - <span>{deActiveLength}</span>个
        </div> */}
        <div>
          {statusButtons.map((item) => (
            <button
              key={item}
              className={item === state.filters.status ? "active" : ""}
              onClick={fn1(item)}
            >
              {item}
            </button>
          ))}
        </div>

        <div>
          {colors.map((item) => (
            <label key={item.id}>
              <input
                type="checkbox"
                value={item.value}
                checked={state.filters.colors.includes(item.value)}
                onChange={fn2(item.value)}
              />
              {item.name}
            </label>
          ))}
        </div>
      </div>
      <button className="todo-clear-button">清空</button>
    </div>
  );
}
